package com.ruoyi.exam.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.exam.vo.ExamRandomPracticeVo;
import com.ruoyi.exam.vo.ExamRandomPracticeQuestionIdsVo;
import com.ruoyi.exam.vo.ExamQuestionDetailVo;
import com.ruoyi.exam.vo.SubmitAnswerVo;
import com.ruoyi.exam.vo.SubmitAnswerResultVo;
import com.ruoyi.exam.service.IExamRandomPracticeService;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.validation.annotation.Validated;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 练习Controller
 *
 * @author Tellsea
 * @date 2025-07-28
 */
@Api(tags = "练习Controller")
@RestController
@RequestMapping("/exam/randomPractice")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class ExamRandomPracticeController extends BaseController {

    private final IExamRandomPracticeService examRandomPracticeService;

    @ApiOperation("查询练习列表")
    @PreAuthorize("@ss.hasPermi('exam:randomPractice:list')")
    @GetMapping("/list")
    public TableDataInfo<ExamRandomPracticeVo> list(ExamRandomPracticeVo entity) {
        return examRandomPracticeService.queryList(entity);
    }

    @ApiOperation("查询练习所有列表")
    @GetMapping("/listAll")
    public AjaxResult listAll(ExamRandomPracticeVo entity) {
        return AjaxResult.success("查询成功", examRandomPracticeService.queryAll(entity));
    }

    @ApiOperation("导出练习列表")
    @PreAuthorize("@ss.hasPermi('exam:randomPractice:export')")
    @Log(title = "练习", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExamRandomPracticeVo entity) {
        List<ExamRandomPracticeVo> list = examRandomPracticeService.queryAll(entity);
        ExcelUtil<ExamRandomPracticeVo> util = new ExcelUtil<>(ExamRandomPracticeVo.class);
        util.exportExcel(response, list, "练习数据");
    }

    @ApiOperation("获取练习详细信息")
    @PreAuthorize("@ss.hasPermi('exam:randomPractice:query')")
    @GetMapping(value = "/getInfo/{practiceId}")
    public AjaxResult getInfo(@PathVariable("practiceId") Long practiceId) {
        return AjaxResult.success("查询成功", examRandomPracticeService.queryById(practiceId));
    }

    @ApiOperation("新增练习")
    @PreAuthorize("@ss.hasPermi('exam:randomPractice:add')")
    @Log(title = "练习", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public AjaxResult add(@RequestBody ExamRandomPracticeVo entity) {
        return toAjax(examRandomPracticeService.save(entity));
    }

    @ApiOperation("修改练习")
    @PreAuthorize("@ss.hasPermi('exam:randomPractice:edit')")
    @Log(title = "练习", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public AjaxResult edit(@RequestBody ExamRandomPracticeVo entity) {
        return toAjax(examRandomPracticeService.updateById(entity));
    }

    @ApiOperation("删除练习")
    @PreAuthorize("@ss.hasPermi('exam:randomPractice:remove')")
    @Log(title = "练习", businessType = BusinessType.DELETE)
	@GetMapping("/remove/{practiceIds}")
    public AjaxResult remove(@PathVariable Long[] practiceIds) {
        return toAjax(examRandomPracticeService.removeByIds(Arrays.asList(practiceIds)) ? 1 : 0);
    }

    @ApiOperation("创建随机练习")
    @Log(title = "创建随机练习", businessType = BusinessType.INSERT)
    @PostMapping("/createRandomPractice")
    public AjaxResult createRandomPractice(@RequestBody ExamRandomPracticeVo entity) {
        //首先判断是否已经有未完成的练习了
        ExamRandomPracticeVo unfinishedPractice = examRandomPracticeService.checkUnfinishedPractice(entity.getBankId(), entity.getQuestionType(), getUserId());
        if (unfinishedPractice != null) {
            return AjaxResult.success("您还有未完成的练习，请先完成当前练习", unfinishedPractice);
        }
        try {
            Long userId = getUserId();
            Long bankId = entity.getBankId();
            String questionType = entity.getQuestionType();
            ExamRandomPracticeVo practice = examRandomPracticeService.createRandomPractice(bankId, questionType, userId);
            return AjaxResult.success("创建练习成功", practice);
        } catch (RuntimeException e) {
            return AjaxResult.success(e.getMessage());
        }
    }

    @ApiOperation("检查是否有未完成的练习")
    @GetMapping("/checkUnfinishedPractice")
    public AjaxResult checkUnfinishedPractice(@RequestParam Long bankId, @RequestParam String questionType) {
        Long userId = getUserId();
        ExamRandomPracticeVo unfinishedPractice = examRandomPracticeService.checkUnfinishedPractice(bankId, questionType, userId);
        if (unfinishedPractice != null) {
            return AjaxResult.success("发现未完成的练习", unfinishedPractice);
        } else {
            return AjaxResult.success("没有未完成的练习", null);
        }
    }

    @ApiOperation("获取随机练习的题目ID列表")
    @GetMapping("/getQuestionIds/{practiceId}")
    public AjaxResult getQuestionIds(@PathVariable("practiceId") Long practiceId) {
        ExamRandomPracticeQuestionIdsVo result = examRandomPracticeService.getQuestionIds(practiceId);
        return AjaxResult.success("查询成功", result);
    }

    @ApiOperation("重新练习")
    @Log(title = "重新练习", businessType = BusinessType.UPDATE)
    @PostMapping("/restartPractice")
    public AjaxResult restartPractice(@RequestBody ExamRandomPracticeVo entity) {
        try {
            Long userId = getUserId();
            Long bankId = entity.getBankId();
            String questionType = entity.getQuestionType();
            
            if (bankId == null) {
                return AjaxResult.error("题库ID不能为空");
            }
            if (questionType == null || questionType.isEmpty()) {
                return AjaxResult.error("题目类型不能为空");
            }
            
            ExamRandomPracticeVo practice = examRandomPracticeService.restartPractice(bankId, questionType, userId);
            return AjaxResult.success("重新练习成功", practice);
        } catch (RuntimeException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("获取随机练习题目详细信息（包含选项、答案、解析等）")
    @GetMapping(value = "/getQuestionDetail/{practiceId}/{questionId}")
    public AjaxResult getQuestionDetail(@PathVariable("practiceId") Long practiceId,
                                        @PathVariable("questionId") Long questionId) {
        try {
            Long userId = getUserId();
            ExamQuestionDetailVo detailInfo = examRandomPracticeService.queryQuestionDetail(practiceId, questionId, userId);
            if (detailInfo == null) {
                return AjaxResult.error("题目不存在");
            }
            return AjaxResult.success("查询成功", detailInfo);
        } catch (RuntimeException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("提交随机练习答案")
    @Log(title = "提交随机练习答案", businessType = BusinessType.INSERT)
    @PostMapping("/submitAnswer")
    public AjaxResult submitAnswer(@Validated @RequestBody SubmitAnswerVo submitAnswerVo) {
        try {
            Long userId = SecurityUtils.getUserId();
            if (submitAnswerVo.getPracticeId() == null) {
                return AjaxResult.error("练习ID不能为空");
            }
            SubmitAnswerResultVo result = examRandomPracticeService.submitAnswer(submitAnswerVo, userId);
            return AjaxResult.success("提交成功", result);
        } catch (Exception e) {
            logger.error("提交答案失败", e);
            return AjaxResult.error("提交答案失败：" + e.getMessage());
        }
    }

    @ApiOperation("完成练习")
    @Log(title = "完成练习", businessType = BusinessType.UPDATE)
    @PostMapping("/completePractice/{practiceId}")
    public AjaxResult completePractice(@PathVariable("practiceId") Long practiceId) {
        try {
            Long userId = getUserId();
            ExamRandomPracticeVo practice = examRandomPracticeService.completePractice(practiceId, userId);
            return AjaxResult.success("完成练习成功", practice);
        } catch (RuntimeException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    
}
